package service;

import java.util.List;

import com.jfinal.aop.Aop;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;

import common.kit.PageSql;
import enums.WxuserRole;
import model.Session;
import model.User;
import model.UserRole;
import model.Wxuser;

public class UserService extends BaseService{

    static LoginService loginService = Aop.get(LoginService.class);
    static UserRoleService userRoleService = Aop.get(UserRoleService.class);

	public Ret saveUser(User user) {
		if (user.isRepeatName()) {
			return fail("用户名已存在");
		}
		user.checkToResetPsw();
		Long id = user.getId();
		if( null == id ) {
			user.save() ;
		}else {
			user.update();
		}
		userRoleService.save( user.getRoleIds() , user.getId() );
		Wxuser.dao.saveForCompany( user.getMobile() , WxuserRole.getManger() , user.getId() );
		this.clearCacheById(user.getId());
		return Ret.ok();
	}

	/**
	 * 根据条件分页查询用户
	 * @param map			查询条件
	 * @param pageNum		查询页数
	 * @param pageSize		一页的数据大小
	 * @return				分页Page
	 */
    public Page<Record> getPage(Kv kv, Integer pageNumber ,Integer pageSize) {
    	kv.set("tu.isDelete", 0);
    	PageSql pageSql = PageSql.bySelect(kv, " tu.* ");
    	pageSql.from(" t_user tu ");
    	pageSql.setEqualCondition("tu.isDelete");
    	pageSql.setEqualCondition("tu.role" , "99");
    	pageSql.setEqualCondition("tu.id");
    	pageSql.setLikeCondition("tu.name");
    	pageSql.orderBy(" tu.createTime DESC ");
        return pageSql.paginate(pageNumber, pageSize);
    }

	/**
	 * 清除用户缓存，在用户状态被改变时需要调用
	 */
	public void clearCacheById(Long userId){
		if(userId == null){
			return;
		}
		List<Session> sessions = Session.dao.findByUserId(userId);
		for (Session session : sessions){
			CacheKit.remove(LoginService.loginUserCacheName, session.getId());
			session.delete();
		}
	}

	
	public Ret changeStatus(Long id , boolean isUsable) {
		User user = User.dao.findById(id);
		if (null == user) {
			return fail() ;
		}
		if (id.equals(User.ADMIN_ID)) {
			return fail("请勿切换超级管理员的状态");
		}
		user.setIsUsable(isUsable);
		user.update();
		if (isUsable == false) {
			String sessionId = user.getSessionId() ;
			loginService.logout(sessionId);
		}
		return ok() ;
	}
	
	public Ret delete(Long id) {
		User user = User.dao.findById(id);
		if (null == user) {
			return fail() ;
		}
		user.setIsDelete(true);
		user.update() ;
		
		loginService.logout(user.getSessionId());
		
		UserRole.dao.deleteByUserId(id);
		
		Wxuser.dao.deleteUser(user.getMobile(), user.getId(), WxuserRole.getManger());
		
		return ok() ;
	}
}
